package org.swim.servlet;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.swim.entity.User;
import org.swim.session.FriendshipManagerRemote;
import org.swim.session.SearchManagerRemote;

/**
 * Servlet implementation class SearchByAbility
 */
public class SearchByAbility extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SearchByAbility() {
        super();  
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
		InitialContext ic;
		try {
			int ability = Integer.parseInt(request.getParameter("ability"));
			String domain = request.getParameter("domain");
			ic = new InitialContext();
			SearchManagerRemote searchManager = (SearchManagerRemote)ic.lookup("SearchManagerRemote");
			List<User> results = searchManager.getSearchByAbilityResult(ability);
			if(domain.equals("friends")) {
				HttpSession session = request.getSession();
				User user = (User) session.getAttribute("user");
				FriendshipManagerRemote friendshipManager = (FriendshipManagerRemote)ic.lookup("FriendshipManagerRemote");
				Iterator<User> iterator = results.iterator();
				while(iterator.hasNext()) {
					User current = iterator.next();
					if(friendshipManager.areFriend(user.getId(), current.getId())==false) {
						iterator.remove();
					}
				}
			}
			request.setAttribute("searchResults", results);
		} catch (NamingException e) {
			e.printStackTrace();
		}  catch (NullPointerException e) {
		}	catch (NumberFormatException e) {
		}
		request.getRequestDispatcher("Search?param=ability").forward(request, response);
	}

}
